package com.laker.admin.module.excel.application.impl;

import com.alibaba.fastjson.JSON;
import com.laker.admin.module.excel.application.ExcelDataApplication;
import com.laker.admin.module.excel.domain.ExcelData;
import com.laker.admin.module.excel.entity.ExcelDataCmd;
import com.laker.admin.module.excel.repository.ExcelDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * @author : nihongxin
 * @date : 2021/3/22
 */
@Component
public class ExcelDataApplicationImpl implements ExcelDataApplication {

    @Autowired
    private ExcelDataRepository excelDataRepository;


    @Override
    public ExcelData save(ExcelData excelData) {
        return excelDataRepository.save(excelData);
    }

    @Override
    public List<ExcelData> getExcelDataList(ExcelDataCmd excelDataCmd) {
        List<Object> excelCoordinatesList = JSON.parseArray(excelDataCmd.getExcelCoordinatesList());
        List<String> excelCoordinatesStringList = excelCoordinatesList.stream().map(o -> String.valueOf(o)).collect(Collectors.toList());
        Specification<ExcelData> specification = (root, query, criteriaBuilder) -> criteriaBuilder.and(
                criteriaBuilder.equal(root.get("excelTemplateId"), excelDataCmd.getExcelTemplateId()),
                criteriaBuilder.equal(root.get("excelTemplateSheetId"), excelDataCmd.getExcelTemplateSheetId()),
                criteriaBuilder.in(root.get("excelCoordinates")).value(excelCoordinatesStringList)
        );
        return excelDataRepository.findAll(specification);
    }

    @Override
    public List<ExcelData> getExcelDataListByExcelTemplateId(Long ExcelTemplateId) {
        Specification<ExcelData> specification = (root, query, criteriaBuilder) -> criteriaBuilder.and(
                criteriaBuilder.equal(root.get("excelTemplateId"), ExcelTemplateId)
        );
        return excelDataRepository.findAll(specification);
    }

    @Override
    public ExcelData getExcelDataByExcelTemplate(ExcelDataCmd excelDataCmd, String excelCoordinates) {
        Specification<ExcelData> specification = (root, query, criteriaBuilder) -> criteriaBuilder.and(
                criteriaBuilder.equal(root.get("excelTemplateId"), excelDataCmd.getExcelTemplateId()),
                criteriaBuilder.equal(root.get("excelTemplateSheetId"), excelDataCmd.getExcelTemplateSheetId()),
                criteriaBuilder.equal(root.get("excelCoordinates"), excelCoordinates)
        );
        Optional<ExcelData> optional = excelDataRepository.findOne(specification);
        return optional.isPresent() ? optional.get() : null;
    }
}
